<template>
  <div class="app-container">
    <div>
      <el-row :gutter="10">
        <el-form
          ref="elForm"
          :model="formData"
          :rules="rules"
          size="mini"
          label-width="125px"
          label-position="right"
        >
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item label="身份证号码" prop="userIdCard">
                  <el-input
                    v-model="formData.userIdCard"
                    placeholder="请输入身份证号码"
                    :maxlength="18"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                    @blur="matchingRequest"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报案人姓名" prop="userName">
                  <el-input
                    v-model="formData.userName"
                    placeholder="请输入报案人姓名"
                    :maxlength="20"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                    @blur="matchingRequest"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item label="出险时间" prop="accidentDate">
                  <el-date-picker
                    type="datetime"
                    align="right"
                    v-model="formData.accidentDate"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :style="{ width: '100%' }"
                    placeholder="请选择出险时间"
                    clearable
                    :picker-options="pickerOptions"
                    @change="matchingRequest"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属公司" prop="companyId">
                  <el-select
                    v-model="formData.companyId"
                    placeholder="请选择所属公司"
                    filterable
                    clearable
                    :disabled="matchingCompany"
                    :style="{ width: '100%' }"
                    @change="changeCompany"
                  >
                    <el-option
                      v-for="(item, index) in companyIdOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item label="公司站点" prop="companySiteId">
                  <el-cascader
                    v-model="formData.companySiteId"
                    :options="companySiteIdOptions"
                    :props="siteProps"
                    :style="{ width: '100%' }"
                    placeholder="请选择公司站点"
                    separator=","
                    filterable
                    clearable
                    @change="changeSiteName"
                    :show-all-levels="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label-width="121px"
                  label="包含附加险"
                  prop="additional"
                >
                  <el-radio-group v-model="formData.additional" size="medium">
                    <el-radio
                      v-for="(item, index) in additionalOptions"
                      :key="index"
                      :label="item.value"
                      :disabled="item.disabled"
                    >{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item label="站长姓名" prop="siteUserName">
                  <el-input
                    v-model="formData.siteUserName"
                    placeholder="请输入站长姓名"
                    :maxlength="20"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="站长手机号" prop="siteUserMobile">
                  <el-input
                    v-model="formData.siteUserMobile"
                    placeholder="请输入站长手机号"
                    :maxlength="11"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item label="骑手手机号" prop="userMobile">
                  <el-input
                    v-model="formData.userMobile"
                    placeholder="请输入骑手手机号"
                    :maxlength="11"
                    show-word-limit
                    clearable
                    :style="{ width: '100%' }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="事故区域" prop="accidentRegionCode">
                  <el-cascader
                    v-model="formData.accidentRegionCode"
                    :options="aredData"
                    :props="accidentRegionCodeProps"
                    :style="{ width: '100%' }"
                    placeholder="请选择事件区域"
                    separator=","
                    filterable
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label-width="110px"
                  label="事故具体地址"
                  prop="accidentAddress"
                >
                  <el-input
                    v-model="formData.accidentAddress"
                    type="textarea"
                    placeholder="请输入事故具体地址"
                    :maxlength="300"
                    show-word-limit
                    :autosize="{ minRows: 1, maxRows: 3 }"
                    :style="{ width: '100%' }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label-width="110px"
                  label="事故概况描述"
                  prop="accidentDesc"
                >
                  <el-input
                    v-model="formData.accidentDesc"
                    type="textarea"
                    placeholder="请输入事故概况描述"
                    :maxlength="500"
                    show-word-limit
                    :autosize="{ minRows: 1, maxRows: 3 }"
                    :style="{ width: '100%' }"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="24">
                <el-form-item label="出险类型" prop="accidentTypeIds">
                  <el-checkbox-group
                    v-model="formData.accidentTypeIds"
                    size="medium"
                  >
                    <el-checkbox
                      v-for="(item, index) in accidentTypeIdsOptions"
                      :key="index"
                      :label="item.value"
                    >{{ item.label }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="24">
                <el-form-item label="责任判定" prop="responsibilityIds">
                  <el-radio-group v-model="formData.responsibilityIds" size="medium">
                    <el-radio v-for="(item, index) in responsibilityIdsOptions"
                      :key="index"
                      :label="item.value">
                      {{ item.label }}
                      </el-radio>
                  </el-radio-group>
                  <!-- <el-checkbox-group v-model="formData.responsibilityIds" size="medium">
                    <el-checkbox
                      v-for="(item, index) in responsibilityIdsOptions"
                      :key="index"
                      :label="item.value"
                      :disabled="item.disabled"
                    >{{ item.label }}</el-checkbox>
                  </el-checkbox-group> -->
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="24">
                <el-form-item label="事故照片" prop="accidentFIles">
                  <el-upload
                    ref="accidentFiles"
                    :file-list="accidentFilesfileList"
                    :action="imagesUploadApi"
                    :headers="authHeaders"
                    :before-upload="accidentFIlesBeforeUpload"
                    :on-success="onUploadSuccess"
                    :on-remove="removeFile"
                    multiple
                    list-type="picture-card"
                    accept="image/*"
                  >
                    <i class="el-icon-plus" />
                    <div slot="tip" class="el-upload__tip">
                      只能上传不超过 5MB 的image/*文件
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="理赔员" prop="responsibleUserId" v-if="formData.id == null || formData.responsibleUserId == null">
                  <el-select
                    v-model="formData.responsibleUserId"
                    placeholder="请选择理赔员"
                    filterable
                    clearable
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(item, index) in responsibleUserIdOptions"
                      :key="index"
                      :label="item.nickName"
                      :value="item.id"
                      :disabled="item.disabled"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
  </div>
</template>
<script>
import aredData from '../../../data/ared.json'
import { getTree } from '@/api/system/dept'
import { getAll } from '@/api/system/user'
import { matching } from '@/api/insurance/user'
import { detail } from '@/api/system/siteUser'
import { apply, loadUpdateData, edit } from '@/api/insurance/case'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  name: 'CaseCreate',
  components: { },
  props: [],
  data() {
    return {
      matchingCompany: false,
      authHeaders: {
        'Authorization': getToken()
      },
      aredData,
      formData: {
        id: null,
        insuredUserId: 0,
        userName: '',
        userIdCard: null,
        accidentDate: null,
        companyId: '',
        companySiteId: '',
        additional: 1,
        siteUserName: '',
        siteUserMobile: '',
        userMobile: null,
        accidentRegionCode: null,
        accidentAddress: null,
        accidentDesc: null,
        accidentTypeIds: [],
        responsibilityIds: null,
        accidentFiles: null,
        responsibleUserId: null
      },
      rules: {
        userName: [
          {
            required: true,
            message: '请输入报案人姓名',
            trigger: 'blur'
          },
          {
            pattern: /[\W]|^[\u4E00-\u9FA5]/g,
            message: '请输入中文或字母',
            trigger: 'blur'
          }
        ],
        userIdCard: [
          {
            required: true,
            message: '请输入身份证号码',
            trigger: 'blur'
          },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '请输入正确的身份证号码',
            trigger: 'blur'
          }
        ],
        accidentDate: [
          {
            required: true,
            message: '请选择出险时间',
            trigger: 'change'
          }
        ],
        companyId: [
          {
            required: true,
            message: '请选择所属公司',
            trigger: 'change'
          }
        ],
        companySiteId: [
          {
            required: true,
            message: '请选择公司站点',
            trigger: 'change'
          }
        ],
        additional: [
          {
            required: true,
            message: '包含附加险不能为空',
            trigger: 'change'
          }
        ],
        siteUserName: [
          {
            required: true,
            message: '请输入站长姓名',
            trigger: 'blur'
          },
          {
            pattern: /[\W]|^[\u4E00-\u9FA5]/g,
            message: '请输入中文或字母',
            trigger: 'blur'
          }
        ],
        siteUserMobile: [
          {
            required: true,
            message: '请输入站长手机号',
            trigger: 'blur'
          },
          {
            pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        userMobile: [
          {
            required: true,
            message: '请输入骑手手机号',
            trigger: 'blur'
          },
          {
            pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        accidentRegionCode: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个事故区域',
            trigger: 'change'
          }
        ],
        accidentAddress: [
          {
            required: true,
            message: '请输入事故具体地址',
            trigger: 'blur'
          }
        ],
        accidentDesc: [
          {
            required: true,
            message: '请输入事故概况描述',
            trigger: 'blur'
          }
        ],
        responsibleUserId: [
          {
            required: true,
            message: '请选择理赔员',
            trigger: 'blur'
          }
        ],
        accidentTypeIds: [],
        responsibilityIds: []
      },
      accidentFilesfileList: [],
      companyDatas: [],
      companySiteDatas: [],
      companyIdOptions: [],
      companySiteIdOptions: [],
      additionalOptions: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      accidentTypeIdsOptions: [
        {
          label: '自身受伤',
          value: 1
        },
        {
          label: '三者受伤',
          value: 2
        },
        {
          label: '三者物损',
          value: 3
        }
      ],
      responsibilityIdsOptions: [
        {
          label: '全责',
          value: '1'
        },
        {
          label: '主责',
          value: '2'
        },
        {
          label: '次责',
          value: '3'
        },
        {
          label: '五五责',
          value: '4'
        },
        {
          label: '无责',
          value: '5'
        },
        {
          label: '摔伤',
          value: '6'
        }
      ],
      responsibleUserIdOptions: [
        {
          nickName: '无理赔员',
          id: 0
        }
      ],
      accidentRegionCodeProps: {
        multiple: false,
        label: 'label',
        value: 'value',
        children: 'children',
        checkStrictly: false
      },
      siteProps: {
        multiple: false,
        label: 'label',
        value: 'id',
        children: 'children',
        checkStrictly: false,
        emitPath: false
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi'
    ])
  },
  watch: {},
  created() {
    getTree().then(res => {
      this.companyDatas = res
      this.companySiteDatas = res
      if (this.$route.query.id) {
        this.companyIdOptions = res
        if (this.formData.companyId) {
          this.changeCompany(this.formData.companyId)
        }
      }
    })
    getAll({ job: '理赔员' }).then(res => {
      if (res != null) {
        this.responsibleUserIdOptions = res
      }
    })
  },
  mounted() {
    if (this.$route.query.id != null) {
      loadUpdateData(this.$route.query.id).then(res => {
        this.formData = res
        this.changeCompany(res.companyId)
        document.title = this.formData.userName + '-修改案件'
        if (this.formData.fileList != null && this.formData.fileList.length > 0) {
          this.accidentFilesfileList = this.formData.fileList.map(n => {
            return { 'realName': n, 'url': this.baseApi + '/file/图片/' + n }
          })
        }
      })

      if (this.formData.id == null) {
        this.formData.id = this.$route.query.id
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.formData.id != null) {
          edit(this.formData).then(res => {
            this.$notify({
              title: '案件录入',
              message: '案件修改成功',
              type: 'success'
            })
            this.resetForm()
            this.$router.replace('/insurance/case')
          })
        } else {
          apply(this.formData).then(res => {
            this.$notify({
              title: '案件录入',
              message: '案件录入成功',
              type: 'success'
            })
            this.resetForm()
            this.$router.go(-1)
            // this.$router.replace('/insurance/case')
          })
        }
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.accidentFilesfileList = []
    },
    accidentFIlesBeforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 5
      if (!isRightSize) {
        this.$message.error('文件大小超过 5MB')
      }
      const isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    onUploadSuccess(response, file, fileList) {
      this.formData.fileList = fileList.map(f => f.response.realName)
    },
    removeFile(file, fileList) {
      if (fileList == null || fileList.length < 1) {
        this.formData.fileList = null
      } else {
        this.formData.fileList = fileList.map(f => f.realName)
      }
    },
    // 选择公司
    changeCompany(company) {
      if (company == null) {
        this.companySiteIdOptions = null
      } else {
        this.companySiteIdOptions = this.companySiteDatas.filter(item => item.id === company).map(item => item)[0].children
      }
    },
    // 选择站长
    changeSiteName(site) {
      if (site) {
        detail(site).then(res => {
          this.formData.siteUserName = res.siteUserName
          this.formData.siteUserMobile = res.siteUserMobile
        })
      }
    },
    // 监听骑手姓名/身份证/出险时间的失去焦点时间，用于匹配当前用户是否有公司
    matchingRequest(vlues) {
      this.formData.insuredUserId = 0
      const matchingUserParam = { 'userName': this.formData.userName, 'userIdCard': this.formData.userIdCard, 'accidentDate': this.formData.accidentDate }

      if (this.formData.userName === '' && this.formData.userIdCard != null && this.formData.userIdCard !== '') {
        matching(matchingUserParam).then(res => {
          if (res != null && res.id != null) {
            this.formData.userName = res.userName
            this.formData.insuredUserId = res.id
            // this.formData.companyId = res.ownerCompanyId
            // this.additional = 1
          }
        })
      } else {
        if (this.formData.userName === '' || this.formData.userIdCard === null || this.formData.userIdCard === '' || this.formData.accidentDate == null) {
          return
        }
        matching(matchingUserParam).then(res => {
          if (res != null && res.id != null) {
            this.formData.insuredUserId = res.id
            this.companyIdOptions = this.companyDatas.filter(item => item.id === res.ownerCompanyId).map(item => item)
            this.formData.companyId = res.ownerCompanyId
            this.additional = 1
          } else {
            this.additional = 0
          }
          this.matchingCompany = (res != null && res.id != null)
          this.changeCompany(res.ownerCompanyId)
        })
      }
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2
}
</style>
